<template>
  <div class="out_div">
    <div v-if="currentMode===currentModeList.LIST" class="baseList">
      <el-form class="searchForm" ref="dictionarySearchForm" size="small"
               :model="dictionarySearchForm">
        <el-row :gutter="5">
          <el-col :span="6">
            <el-form-item prop="name" label="数据名称:">
              <el-input clearable placeholder="请输入名字"
                        v-model="dictionarySearchForm.name"
                        name="name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="code" label="编码:">
              <el-input clearable placeholder="请输入编码"
                        v-model="dictionarySearchForm.code"
                        name="code"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button icon="el-icon-search" type="primary" size="mini"
                       @click="searchDictionaryHandler">查询
            </el-button>
            <el-button icon="el-icon-refresh-right" type="info" size="mini"
                       @click="resetDictionaryHandler">重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <toolbar @on-add="addDictionaryHandler" :privileges="btnPrivileges"
               :keys="['add']"/>
      <paginatable :keys="['edit','del']" :privileges="btnPrivileges"
                   v-loading="dictionaryTblOpts.loading"
                   @row-edit="editDictionaryHandler"
                   @row-del="delDictionaryHandler"
                   @on-pagination="paginationDictionaryHandler"
                   :tblOpts="dictionaryTblOpts"/>
    </div>
    <el-container v-if="currentMode===currentModeList.EDIT" class="baseEdit">
      <el-header style="height: 35px;padding: 0">
        <el-row>
          <el-col :span="12">
            <el-page-header @back="backHandler" content="详情页面">
            </el-page-header>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-form :rules="rules" v-loading="formLoading" class="editForm" size="small" label-width="90px"
                 :model="dictionaryEditForm"
                 ref="dictionaryEditForm">
          <el-form-item class="hidden" prop="id">
            <el-input v-model="dictionaryEditForm.id" type="hidden"/>
          </el-form-item>
          <el-row :gutter="5">
            <el-col :span="10">
              <el-form-item label="名称:" prop="name">
                <el-input clearable style="width: 100%"
                          v-model="dictionaryEditForm.name"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="10">
              <el-form-item label="编码:" prop="code">
                <el-input clearable style="width: 100%"
                          v-model="dictionaryEditForm.code"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="10">
              <el-form-item label="字典级别:" prop="type">
                <el-select v-model="dictionaryEditForm.type">
                  <el-option label="平台" :value="1"></el-option>
                  <el-option label="账户" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="18">
              <el-form-item label="字典类别:">
                <el-select v-model="dictionaryEditForm.accountType">
                  <el-option label="通用" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="10">
              <el-form-item label="备注:" prop="remark">
                <el-input clearable style="width: 100%"
                          v-model="dictionaryEditForm.remark"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider content-position="left">字典值列表</el-divider>
        <toolbar @on-add="addChildItemHandler" :privileges="btnPrivileges"
                 :keys="['add']"/>
        <el-table
            border
            height="300px"
            :data="childList"
            style="width:70%"
            :header-cell-style="{background:'#F8F8F8'}">
          <el-table-column prop="code" label="字典CODE"></el-table-column>
          <el-table-column prop="value" label="字典值"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column :show-overflow-tooltip="true"
                           label="操作"
                           align="center"
                           fixed="right">
            <template slot-scope="scope">
              <el-button @click="editChildHandler(scope)"
                         type="text" style="margin-right: 10px" plain size="mini"
                         icon="el-icon-edit">编辑
              </el-button>
              <el-button @click="delChildHandler(scope)"
                         type="text" style="margin-right: 10px" plain size="mini"
                         icon="el-icon-edit">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-main>
      <el-footer>
        <toolbar @on-save="saveDictionaryHandler" :privileges="btnPrivileges"
                 :keys="['save']"/>
      </el-footer>
    </el-container>
    <el-dialog title="新增字典值" show-close :visible.sync="dialogOpt.show" width="20%">
      <el-form :rules="rules" v-loading="formLoading" class="editForm" size="small" label-width="90px"
               :model="dialogOpt.data"
               ref="childDictionaryFrom">
        <el-form-item class="hidden" prop="id">
          <el-input v-model="dialogOpt.data.id" type="hidden"/>
        </el-form-item>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="编码:" prop="code">
              <el-input clearable style="width: 100%"
                        v-model="dialogOpt.data.code"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="字典值:" prop="value">
              <el-input clearable style="width: 100%"
                        v-model="dialogOpt.data.value"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="备注:" prop="remark">
              <el-input clearable style="width: 100%"
                        v-model="dialogOpt.data.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="width: 100%;text-align: center">
          <toolbar @on-save="saveChildHandler" :privileges="btnPrivileges"
                   :keys="['save']"/>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import paginatable from '@/components/paginatable'
import toolbar from '@/components/toolbar'
import * as tools from '@/utils/tools'
import * as dictionaryApi from '@/api/sys/dictionary'
import * as menuApi from '@/api/sys/menu'

export default {
  name: 'dictionary',
  data() {
    return {
      childList: [],
      dialogOpt: {
        show: false,
        isEdit: false,
        editIndex: -1,
        data: {
          id: '',
          value: '',
          code: '',
          remark: ''
        }
      },
      rules: {
        name: [{required: true, message: '请输入字典名称', trigger: 'change'}],
        value: [{required: true, message: '请输入字典值', trigger: 'change'}],
        code: [{required: true, message: '请输入字典CODE', trigger: 'change'}]
      },
      currentModeList: this.$config.currentShow,
      currentMode: this.$config.currentShow.LIST,
      formLoading: false,
      dictionarySearchForm: {
        id: '',
        name: '',
        code: '',
        value: '',
        parentsId: '',
        lvl: '',
        remark: '',
      },
      dictionaryEditForm: {
        id: '',
        name: '',
        code: '',
        type: '',
        accountType: '',
        value: '',
        parentsId: '',
        lvl: '',
        remark: '',
      },
      dictionaryTblOpts: {
        fitCols: true, loading: false,
        cols: [
          {
            prop: 'name',
            label: '名字'
          },
          {
            prop: 'code',
            label: '编码'
          },
          {
            prop: 'remark',
            label: '备注'
          },
        ],
        data: [],
        selection: []
      },
      btnPrivileges: [],
      searchDictionaryConditions: []
    }
  },
  components: {
    paginatable,
    toolbar
  },
  methods: {
    resetDictionaryHandler() {
      this.$refs.dictionarySearchForm.resetFields()
      this.searchDictionaryHandler()
    },
    clearEdit() {
      if (this.$refs.dictionaryEditForm) {
        this.$refs.dictionaryEditForm.resetFields()
        this.childList = []
      }
    },
    backHandler() {
      this.formLoading = false
      this.currentMode = this.$config.currentShow.LIST
      this.clearEdit()
      this.paginationDictionaryHandler()
    },
    delChildHandler(scope) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let index = scope.$index
        this.childList.splice(index, 1)
      });
    },
    editChildHandler(scope) {
      let row = scope.row
      let index = scope.$index
      this.dialogOpt.show = true
      this.dialogOpt.isEdit = true
      this.dialogOpt.editIndex = index
      this.dialogOpt.data = JSON.parse(JSON.stringify(row))
    },
    async saveChildHandler() {
      let valid = await this.$refs.childDictionaryFrom.validate()
      if (valid) {
        if (this.dialogOpt.isEdit) {
          this.childList.splice(this.dialogOpt.editIndex, 1, JSON.parse(JSON.stringify(this.dialogOpt.data)))
        } else {
          this.childList.push(JSON.parse(JSON.stringify(this.dialogOpt.data)))
        }
        if (this.$refs.childDictionaryFrom) {
          console.log('到这里了 ')
          this.$refs.childDictionaryFrom.resetFields()
        }
        this.$nextTick(() => {
          this.dialogOpt.show = false
        })
      }
    },
    async saveDictionaryHandler() {
      let valid = await this.$refs.dictionaryEditForm.validate()
      if (valid) {
        this.formLoading = true
        this.dictionaryEditForm.childList = this.childList
        dictionaryApi.save(this.dictionaryEditForm).then(resp => {
          this.formLoading = true
          tools.notify({
            type: 'success',
            message: '保存成功'
          })
          this.backHandler()
        }).catch(resp => {
          this.formLoading = false
        })
      } else {
        tools.notify({
          type: 'warning',
          message: '请按要求填写'
        })
      }
    },
    delDictionaryHandler(row) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        dictionaryApi.del(row.id).then(resp => {
          this.paginationDictionaryHandler(this.dictionaryTblOpts.pageNo)
          tools.notify({
            type: 'success',
            message: '删除成功'
          })
        })
      }).catch(() => {
      })
    },
    addChildItemHandler() {
      this.dialogOpt.show = true
      this.dialogOpt.isEdit = false
      this.dialogOpt.editIndex = -1
    },
    addDictionaryHandler() {
      this.currentMode = this.$config.currentShow.EDIT
      this.clearEdit()
    },
    editDictionaryHandler(row) {
      this.currentMode = this.$config.currentShow.EDIT
      this.clearEdit()
      dictionaryApi.load(row.id).then(resp => {
        tools.assignVal(this.dictionaryEditForm, resp.data)
        this.childList = resp.data.childList || []
      })
    },
    searchDictionaryHandler() {
      this.searchDictionaryConditions = []
      if (this.dictionarySearchForm.name) {
        let val = this.dictionarySearchForm.name
        this.searchDictionaryConditions.push({
          field: 'name',
          operator: 'like',
          values: val instanceof Array ? [...val] : [val]
        })
      }
      if (this.dictionarySearchForm.code) {
        let val = this.dictionarySearchForm.code
        this.searchDictionaryConditions.push({
          field: 'code',
          operator: 'like',
          values: val instanceof Array ? [...val] : [val]
        })
      }
      this.paginationDictionaryHandler()
    },
    paginationDictionaryHandler(pageNo) {
      this.$set(this.dictionaryTblOpts, 'pageNo', pageNo || 1)
      this.dictionaryTblOpts.loading = true
      dictionaryApi.pagination(this.dictionaryTblOpts, this.searchDictionaryConditions).then(resp => {
        this.dictionaryTblOpts.data = resp.data.records
        Object.assign(this.dictionaryTblOpts, {total: Number(resp.data.total)})
        this.dictionaryTblOpts.loading = false
      })
    }
  },
  mounted() {
    let menuId = this.$route.meta.id
    menuApi.getMenuBtn(menuId).then(resp => {
      this.btnPrivileges = resp.data
    })
    this.paginationDictionaryHandler()
  }
}
</script>
